package bma.common.langutil.ai.stack;

import bma.common.langutil.core.Preconditions;

/**
 * 
 * @author guanzhong
 * @since 1.0 (imported from BMA.ESP Project)
 *
 * @param <RESP_TYPE>
 */
public abstract class AISRun<RESP_TYPE> implements AIStackRunnable<RESP_TYPE> {

	private AIStack<RESP_TYPE> stack;

	public AISRun() {
		super();
	}

	public AISRun(AIStack<RESP_TYPE> stack) {
		super();
		setStack(stack);
	}

	public AIStack<RESP_TYPE> getStack() {
		return stack;
	}

	@Override
	public void bindStack(AIStack<RESP_TYPE> stack) {
		if (this.stack != null) {
			throw new IllegalStateException("stack binded");
		}
		setStack(stack);
	}

	protected void setStack(AIStack<RESP_TYPE> s) {
		stack = s;
	}

	protected boolean end(RESP_TYPE v, Throwable t) {
		if (t != null) {
			return failure(t);
		} else {
			return success(v);
		}
	}

	public boolean success(RESP_TYPE result) {
		return stack.success(result);
	}

	public boolean failure(Throwable t) {
		return stack.failure(t);
	}

	@Override
	public void run() {
		Preconditions.checkNotNull(this.stack);
		try {
			execute();
		} catch (Throwable e) {
			try {
				failure(e);
			} catch (Exception e2) {
			}
		}
	}

	public abstract void execute();
}
